package com.alipay.rebate.shop.scheduler.orderimport;

import com.alipay.rebate.shop.constants.*;
import com.alipay.rebate.shop.dao.mapper.*;
import com.alipay.rebate.shop.helper.*;
import com.alipay.rebate.shop.model.*;
import com.alipay.rebate.shop.pojo.dingdanxia.PddOrdersResponse;
import com.alipay.rebate.shop.pojo.dingdanxia.PddOrdersRsp;
import com.alipay.rebate.shop.pojo.user.admin.AdminImportPddOrders;
import com.alipay.rebate.shop.pojo.user.admin.ImportPddOrders;
import com.alipay.rebate.shop.pojo.user.customer.UserCouponRsp;
import com.alipay.rebate.shop.utils.DateUtil;
import com.alipay.rebate.shop.utils.DecimalUtil;
import com.alipay.rebate.shop.utils.DingdanxiaUtil;
import com.alipay.rebate.shop.utils.ListUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class PddOrdersImport extends AbstractJdAndPddOrdersImport {

    private Logger logger = LoggerFactory.getLogger(PddOrdersImport.class);

    @Autowired
    PddOrdersMapper pddOrdersMapper;
    @Autowired
    UserJdPidMapper userJdPidMapper;
    @Autowired
    UserIncomeMapper userIncomeMapper;
    @Autowired
    UserGradeMapper userGradeMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    CommissionFreezeLevelSettingsMapper commissionFreezeLevelSettingsMapper;
    @Autowired
    CommissionLevelSettingsMapper commissionLevelSettingsMapper;
    @Resource
    UserIncomeHelper userIncomeHelper;
    @Resource
    IncomeCommissionFreezeLevelHelper incomeCommissionFreezeLevelHelper;
    @Autowired
    CouponGetRecordMapper couponGetRecordMapper;
    @Autowired
    InviteSettingsMapper inviteSettingsMapper;
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    JdOrdersMapper jdOrdersMapper;

    private static final int FREEZE_TYPE = 1;
    Gson gson = new Gson();

    @Transactional
    public void importOrders(Long startUpdateTime, Long endUpdateTime, Integer pageSize, Integer page)
            throws IOException, ParseException {

        PddOrdersRsp pddOrders = DingdanxiaUtil.getPddOrders(startUpdateTime, endUpdateTime, pageSize, page);

        logger.debug("pddOrders is : {}",pddOrders);

        //获取导入的订单信息
        List<PddOrdersResponse> pddOrdersRsp = pddOrders.getData();

        for (PddOrdersResponse orders : pddOrdersRsp){

            PddOrders pddOrder = buildPddOrders(orders);

            logger.debug("pddOrder is : {}",pddOrder);

            //处理订单
            dealWithOrder(pddOrder);
        }
    }

    public void dealWithOrder(PddOrders pddOrder){

        logger.debug("pddOrders pid is : {}",pddOrder.getpId());
        //获取用户id
        Long userId = userJdPidMapper.selectUserIdByPddPId(pddOrder.getpId());
        //用户id为空
        if (userId == null){
            pddOrder.setIsRecord(0);
            saveOrUpdateOrders(pddOrder);
            return;
        }
        pddOrder.setUserId(userId);
        pddOrder.setIsRecord(1);
        logger.debug("pddOrdersUserId is : {}",pddOrder.getUserId());
        User user = userMapper.selectUserByUserId(userId);
        pddOrder.setUserName(user.getUserNickName());
        PddOrders preOrders = pddOrdersMapper.selectPddOrdersByOrderSn(pddOrder.getOrderSn());
        logger.debug("orders is : {}",preOrders);
        if (preOrders == null){
            //用户订单数加1
            countUserOrdersNum(pddOrder.getUserId());
        }
        if (preOrders != null) {
            if (checkOrdersStatus(pddOrder,preOrders,user)){
                logger.debug("checkOrdersStatus is true");
                return;
            }
        }
        //判断是否需要冻结，并创建收益记录
        handleDifferentOrdersStatus(pddOrder,userId,user,preOrders);
        //保存或更新订单信息
        saveOrUpdateOrders(pddOrder);
    }

    private Boolean checkOrdersStatus(PddOrders pddOrder,PddOrders preOrders,User user){
        CommissionFreezeLevelSettings freezeSettingsByMoney = getFreezeSettingsByMoney(preOrders.getUserCommission(),FREEZE_TYPE);
        logger.debug("freezeSettingsByMoney is : {}",freezeSettingsByMoney);
        //订单存在，并且订单状态一致，不进行处理
        if (pddOrder.getOrderStatus() == preOrders.getOrderStatus()) {
            logger.debug("orderStatus equals");
            return true;
        }
        //已处理过的订单不需要再次处理
        // 已支付到已成团状态
        logger.debug("ordersStatus : {},{}",preOrders.getOrderStatus(),pddOrder.getOrderStatus());
        if (preOrders.getOrderStatus() == PddOrdersConstant.PDD_PAID_STATUS &&
                pddOrder.getOrderStatus() == PddOrdersConstant.PDD_CLUSTERING_STATUS){
            logger.debug("ordersStatus paid ~ clustering");
            // 创建或更新收益记录
            createIncomeRecord(pddOrder,user,freezeSettingsByMoney);
            saveOrUpdateOrders(pddOrder);
            return true;
        }
        //已支付到已收货
        if (preOrders.getOrderStatus() == PddOrdersConstant.PDD_PAID_STATUS &&
                pddOrder.getOrderStatus() == PddOrdersConstant.PDD_CONFIRM_RECEIPT_STATUS){
            logger.debug("ordersStatus paid ~ confirmReceipt");
            saveOrUpdateOrders(pddOrder);
            // 创建或更新收益记录
            createIncomeRecord(pddOrder,user,freezeSettingsByMoney);
            return true;
        }
        //已支付到审核成功
        if (preOrders.getOrderStatus() == PddOrdersConstant.PDD_PAID_STATUS &&
                pddOrder.getOrderStatus() == PddOrdersConstant.PDD_SUCCESS_STATUS){
            // 创建或更新收益记录
            logger.debug("ordersStatus paid ~ success");
            createIncomeRecord(pddOrder,user,freezeSettingsByMoney);
            saveOrUpdateOrders(pddOrder);
            return true;
        }
        //已成团到确认收货状态，
        if (pddOrder.getOrderStatus() == PddOrdersConstant.PDD_CONFIRM_RECEIPT_STATUS
                && preOrders.getOrderStatus() == PddOrdersConstant.PDD_CLUSTERING_STATUS
        ){
            logger.debug("orderStatus confirmReceipt ~ clustering");
            // 创建或更新收益记录
            createIncomeRecord(pddOrder,user,freezeSettingsByMoney);
            saveOrUpdateOrders(pddOrder);
            return true;
        }
        return false;
    }

    //根据不同状态判断是否需要冻结佣金
    private void handleDifferentOrdersStatus(PddOrders orders, Long userId, User user,PddOrders preOrders){

        logger.debug("checkOrdersStatus start");
        //无佣金订单不需要处理
        if (orders.getOrderStatus() == 8){
            return;
        }
        if (beforeAccountsAndAccountStatus(orders)){
            // 活动订单
            dealwithActivityOrdersLogicIfis(orders,preOrders,userId);
            // 计算用户佣金，用户上级佣金，上上级佣金，上上上级佣金
            countCommission(orders,user,0,orders.getPromotionAmount(),orders.getGoodsPrice());
            logger.debug("orders userCommission is : {}",orders.getUserCommission());
            CommissionFreezeLevelSettings freezeSettingsByMoney = getFreezeSettingsByMoney(orders.getUserCommission(),FREEZE_TYPE);
            logger.debug("freezeSettingsByMoney is : {}",freezeSettingsByMoney);
            //创建收益记录
            createIncomeRecord(orders,user,freezeSettingsByMoney);
            //订单结算状态
            if (PddOrdersConstant.PDD_ACCOUNTING_STATUS.equals(orders.getOrderStatus())){
                checkIsFirstBatchOrders(user,userId,orders);
                //不冻结，直接增加用户的集分宝
                plusUserIntgeralTreasure(freezeSettingsByMoney,orders,user);
            }
        }
        //失效订单
        if (PddOrdersConstant.PDD_OVERDUE_STATUS.equals(orders.getOrderStatus())){
            handleOverDueOrders(orders.getOrderSn());
        }
        logger.debug("checkOrdersStatus end");
    }

    private void plusUserIntgeralTreasure(CommissionFreezeLevelSettings freezeSettingsByMoney,PddOrders orders,User user){
        if (freezeSettingsByMoney == null){
            plusUserUit(orders.getUserUit(),orders.getOneLevelUserUit(),orders.getTwoLevelUserUit(),user);
        }
        if (freezeSettingsByMoney != null){
            if (freezeSettingsByMoney.getFreezeDay() == 0){
                plusUserUit(orders.getUserUit(),orders.getOneLevelUserUit(),orders.getTwoLevelUserUit(),user);
            }
        }
    }

    private void checkIsFirstBatchOrders(User user,Long userId,PddOrders orders){
        //判断是否是第一笔完成的订单
        Long jdCount = jdOrdersMapper.selectCountByUserId(user.getUserId());
        logger.debug("jdOrders is : {}",jdCount);
        Long count = ordersMapper.selectCountByUserId(user.getUserId());
        Long pddCount = pddOrdersMapper.selectCountByUserId(user.getUserId());

        if (jdCount < 1 && count < 1 && pddCount < 1){
            // 新用户
            checkNewUser(userId,orders.getOrderStatus());
            if (user.getParentUserId() != null){
                // 拉新奖励
                Long awardNum = checkAndAwardToUser(user, orders.getGoodsPrice());
                // 插入拉新收益明细
                insertPddOrdersPullNewUserIncome(orders,awardNum,user);
            }

        }
    }

    //创建收益记录
    private void createIncomeRecord(PddOrders orders,User user,
                                    CommissionFreezeLevelSettings freezeSettingsByMoney ){
        logger.debug("createIncomeRecord start");
        //查询订单是否已存在
        PddOrders pddOrders = pddOrdersMapper.selectPddOrdersByOrderSn(orders.getOrderSn());

        if (pddOrders == null){
            insertUserIncome(orders,user,freezeSettingsByMoney);
        }else{
            // 查询数据库是否已经有用户记录
            List<UserIncome> userIncomeList = userIncomeMapper
                    .selectUserIncomeByOrdersId(orders.getOrderSn());
            logger.debug("userIncomeList is : {}",userIncomeList);
            if(userIncomeList.size() > 0) {
                logger.debug("update userIncome");
                updateUserIncome(orders, user, userIncomeList, freezeSettingsByMoney);
            }else{
                insertUserIncome(orders,user,freezeSettingsByMoney);
            }
        }
        logger.debug("createIncomeRecord end");
    }

    protected void insertUserIncome(
            PddOrders orders, User user,CommissionFreezeLevelSettings freezeCommissionSettings
    ){

        logger.debug("insertUserIncome start");
        BigDecimal userCommission = orders.getUserCommission();
        BigDecimal oneLevelCommission = orders.getOneLevelCommission();
        BigDecimal twoLevelCommission = orders.getTwoLevelCommission();
        // 往用户收益表插入记录
        // 1 购买用户本人
        Integer roadType = 0;
        insertUserIncome(orders,userCommission,user.getUserId(),roadType,freezeCommissionSettings);
        if (orders.getActivityId() != null){
            // 活动订单，上级，上上级用户佣金不计算
            return;
        }

        // 2 推广人，即上级用户
        if (user.getParentUserId() != null){
            roadType = 1;
            insertUserIncome(orders,oneLevelCommission,user.getParentUserId(),roadType,freezeCommissionSettings);
            User parentUser = userMapper.selectById(user.getParentUserId());
            if (parentUser.getParentUserId() != null){
                roadType = 2;
                insertUserIncome(orders,twoLevelCommission,parentUser.getParentUserId(),roadType,freezeCommissionSettings);
            }
        }
        logger.debug("insertUserIncome end");
    }

    protected void insertUserIncome(
            PddOrders orders,
            BigDecimal money,
            Long userId,
            Integer roadType,
            CommissionFreezeLevelSettings freezeCommissionSettings
    ){
        logger.debug("insertUserIncome freezeCommissionSettings is : {}",freezeCommissionSettings);
        boolean freezeCommission = false;
        if (freezeCommissionSettings != null){
            if (freezeCommissionSettings.getFreezeDay() != 0){
                logger.debug("freezeCommission");
                freezeCommission = true;
            }
        }
        UserIncome userIncome = userIncomeHelper.insertPddOrderCommissionIncome(orders,money,userId,roadType,freezeCommission);
        if(freezeCommissionSettings != null){
            incomeCommissionFreezeLevelHelper.insert(userIncome.getUserIncomeId(),
                    freezeCommissionSettings.getId());
        }
    }

    protected void updateUserIncome(
            PddOrders orders,
            User user,
            List<UserIncome> userIncomeList,
            CommissionFreezeLevelSettings freezeCommissionSettings
    ){
        logger.debug("updateUserIncome start");
        BigDecimal userCommission = orders.getUserCommission();
        BigDecimal oneLevelCommission = orders.getOneLevelCommission();
        BigDecimal twoLevelCommission = orders.getTwoLevelCommission();
        // 往用户收益表插入记录
        // 1 购买用户本人
        UserIncome userIncome = getUserIncomeIdFromList(userIncomeList,user.getUserId());
        updateUserIncome(userIncome,userCommission,orders.getOrderStatus().longValue(),freezeCommissionSettings);
        if (orders.getActivityId() != null){
            // 活动订单，上级，上上级用户佣金不计算
            return;
        }
        // 2 推广人，即上级用户
        if (user.getParentUserId() != null){
            UserIncome parentIncome = getUserIncomeIdFromList(userIncomeList,user.getParentUserId());
            updateUserIncome(parentIncome,oneLevelCommission,orders.getOrderStatus().longValue(),freezeCommissionSettings);
            User parentUser = userMapper.selectById(user.getParentUserId());
            if (parentUser.getParentUserId() != null){
                UserIncome income = getUserIncomeIdFromList(userIncomeList,parentUser.getParentUserId());
                updateUserIncome(income,twoLevelCommission,orders.getOrderStatus().longValue(),freezeCommissionSettings);
            }
        }
        logger.debug("updateUserIncome end");
    }

    private void updateUserIncome(
            UserIncome preIncome, BigDecimal money, Long tkStatus,
            CommissionFreezeLevelSettings freezeCommissionSettings
    ){
        logger.debug("userIncome is : {}",preIncome);
        UserIncome userIncome = new UserIncome();
        userIncome.setUserIncomeId(preIncome.getUserIncomeId());
        userIncome.setMoney(money);
        userIncome.setTkStatus(tkStatus);
        userIncome.setStatus(0);

        logger.debug("updateUserIncome freezeCommissionSettings is ");
        if (tkStatus.intValue()==PddOrdersConstant.PDD_ACCOUNTING_STATUS){
            logger.debug("tkStatus is 5");
            if(freezeCommissionSettings == null ){
                userIncome.setStatus(UserIncomeConstant.IS_PAID);
            } else {
                userIncome.setStatus(getIncomeStatusWhenUpdate(preIncome,PddOrdersConstant.PDD_ACCOUNTING_STATUS));
            }
            if (freezeCommissionSettings != null){
                if (freezeCommissionSettings.getFreezeDay() == 0){
                    userIncome.setStatus(UserIncomeConstant.IS_PAID);
                }
            }
        }
        userIncome.setUpdateTime(DateUtil.getNowStr());
        logger.debug("update UserIncome is: {}",userIncome);
        userIncomeMapper.updateUserIncomeByUserIncome(userIncome);
    }

    //判断订单是否已经存在
    private void saveOrUpdateOrders(PddOrders orders) {

        logger.debug("orders.getOrderStatus() is : {}",orders.getOrderStatus());
        logger.debug("orders.getOrderStatus() is : {}",orders.getOrderStatusDesc());

        PddOrders pddOrders = pddOrdersMapper.selectPddOrdersByOrderSn(orders.getOrderSn());

        logger.debug("pddOrders is : {}", pddOrders);

        //数据库没有此订单
        if (pddOrders == null) {
            logger.debug("insert pddOrders");
            pddOrdersMapper.insert(orders);
        } else {
            logger.debug("update pddOrders");
            pddOrdersMapper.updatePddOrders(orders);
        }
    }

    //准备订单信息
    private PddOrders buildPddOrders(PddOrdersResponse response) throws ParseException {

        PddOrders pddOrders = new PddOrders();
        pddOrders.setOrderId(response.getOrder_id());
        pddOrders.setOrderSn(response.getOrder_sn());
        pddOrders.setCpaNew(response.getCpa_new());
        pddOrders.setGoodsId(response.getGoods_id());
        pddOrders.setGoodsName(response.getGoods_name());
        BigDecimal price = new BigDecimal(response.getGoods_price());
        logger.debug("price is : {}",price);
        BigDecimal divid = new BigDecimal(100);
        logger.debug("divide is : {}",divid);
        BigDecimal goodsPrice = price.divide(divid);
        logger.debug("goodsPrice is : {}",goodsPrice);
        pddOrders.setGoodsPrice(goodsPrice);
        pddOrders.setGoodsQuantity(response.getGoods_quantity());
        pddOrders.setGoodsThumbnailUrl(response.getGoods_thumbnail_url());
        BigDecimal bigDecimal = new BigDecimal(response.getOrder_amount());
        BigDecimal orderAmount = bigDecimal.divide(divid);
        pddOrders.setOrderAmount(orderAmount);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (response.getOrder_create_time() != null){
            Long createTime = response.getOrder_create_time()*1000;
            String ordersCreateTime = format.format(createTime);
            pddOrders.setOrderCreateTime(ordersCreateTime);
        }
        if (response.getOrder_group_success_time() != null) {
            Long order_group_success_time = response.getOrder_group_success_time() * 1000;
            pddOrders.setOrderGroupSuccessTime(format.format(order_group_success_time));
        }
        if (response.getOrder_modify_at() != null){
            Long orderModifyAt = response.getOrder_modify_at()*1000;
            pddOrders.setOrderModifyAt(format.format(orderModifyAt));
        }
        if (response.getOrder_pay_time() != null){
            Long order_pay_time = response.getOrder_pay_time()*1000;
            pddOrders.setOrderPayTime(format.format(order_pay_time));
        }
        if (response.getOrder_verify_time() != null) {
            Long order_verify_time = response.getOrder_verify_time()*1000;
            pddOrders.setOrderVerifyTime(format.format(order_verify_time));
        }
//        logger.debug("response.getCustom_parameters() is : {}",response.getCustom_parameters());
//        if (response.getCustom_parameters().equals(" ")){
//            pddOrders.setCustomParameters(null);
//            logger.debug("getCustom_parameters is : {}",pddOrders.getCustomParameters());
//        }

        pddOrders.setCustomParameters(response.getCustom_parameters());
        logger.debug("setCustomParameters is : {}",pddOrders.getCustomParameters());
        pddOrders.setOrderStatus(response.getOrder_status());
        pddOrders.setOrderStatusDesc(response.getOrder_status_desc());
        pddOrders.setpId(response.getP_id());
        BigDecimal bigDecimal1 = new BigDecimal(response.getPromotion_amount());
        pddOrders.setPromotionAmount(bigDecimal1.divide(divid));
        pddOrders.setPromotionRate(response.getPromotion_rate());
        return pddOrders;

    }

    private Boolean beforeAccountsAndAccountStatus(PddOrders pddorders){
        return PddOrdersConstant.PDD_PAID_STATUS.equals(pddorders.getOrderStatus()) ||
                PddOrdersConstant.PDD_CLUSTERING_STATUS.equals(pddorders.getOrderStatus()) ||
                PddOrdersConstant.PDD_UNPAID_STATUS.equals(pddorders.getOrderStatus()) ||
                PddOrdersConstant.PDD_CONFIRM_RECEIPT_STATUS.equals(pddorders.getOrderStatus()) ||
                PddOrdersConstant.PDD_SUCCESS_STATUS.equals(pddorders.getOrderStatus()) ||
                PddOrdersConstant.PDD_ACCOUNTING_STATUS.equals(pddorders.getOrderStatus());
    }

}
